package study.springboot.redis.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.RedisClientInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import study.springboot.redis.support.result.Result;
import study.springboot.redis.support.result.Results;
import study.springboot.redis.support.result.Sleeps;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/get")
    public Result get(@RequestParam(defaultValue = "0") long timeout) {
        String value = (String) redisTemplate.opsForValue()
                .get("key");
        log.info(">>>>>> {}", value);
        Sleeps.sleep(timeout);
        return Results.ok();
    }

    @RequestMapping("/set")
    public Result set(@RequestParam(defaultValue = "0") long timeout) {
        redisTemplate.opsForValue().set("x", "");
        Sleeps.sleep(timeout);
        return Results.ok();
    }

    @RequestMapping("/getClientInfoLt")
    public Result getClients() {
        List<RedisClientInfo> clientInfoLt = redisTemplate.getClientList();
        List<RedisClientInfo> myClientInfoLt = clientInfoLt.stream()
                .filter(e -> !"client".equals(e.getLastCommand()))
                .collect(Collectors.toList());
        myClientInfoLt.forEach(e -> {
            log.info(">>>>>> {} {}, {}", e.getName(), e.getLastCommand(), e.getAge());
        });
        return Results.ok();
    }
}
